import React, { Component } from 'react'
import { Card, Select, Input, Button, Icon, Table, message } from "antd";

import LinkButton from "../../components/link-button";
import { reqProducts, reqSearchProducts, reqUpdateProductStatus } from "../../api/index";
import { PAGE_SIZE } from "../../utils/constants";

const Option = Select.Option;

export default class ProductHome extends Component {
    state = {
        total: 0, // 商品的总数量
        products: [], // 商品的数组
        loading: false, // 加载开关
        searchName: '', // 搜索的关键字
        searchType: 'productName', // 根据那个字段搜索
    }

    // 初始化表格的列数组
    initColumns = () => {
        this.columns = [
            {
                title: '商品名称',
                dataIndex: 'name'
            },
            {
                title: '商品描述',
                dataIndex: 'desc'
            },
            {
                title: '价格',
                dataIndex: 'price', // 当前指定了对应的属性
                reder: (price) => '￥' + price // 传入的是对应的属性值
            },
            {
                width: 100,
                title: '状态',
                // dataIndex: 'status',
                render: (product) => {
                    const {status, _id} = product;
                    const newStatus = status === 1 ? 2 : 1;
                    return (
                        <span>
                            <Button 
                            type='primary' 
                            onClick={() => this.updateStatus(_id, newStatus)}
                            >
                                {status === 1 ? '下架' : '上架'}
                            </Button>
                            <span>{status === 1 ? '在售' : '已下架'}</span>
                        </span>
                    )
                }
            },
            {
                width: 100,
                title: '操作',
                render: (product) => {
                    return (
                        <span>
                            {/* 将 product 对象使用 state 传递给目标路由组件 */}
                            <LinkButton onClick={() => this.props.history.push('product/detail', {product})}>详情</LinkButton>
                            <LinkButton onClick={() => this.props.history.push('product/addupdate', product)}>修改</LinkButton>
                        </span>
                    )
                }
            },
        ]
    }

    // 获取指定页面的列表数据显示
    getProducts = async (pageNum) => {
        this.pageNum = pageNum; // 保存 pageNum,让其他方法可以看到，用来上/下架商品
        this.setState({loading: true}); // 显示 loading 

        const { searchName, searchType } = this.state;
        let result;
        if(searchName) { // 如果搜索关键字有值，说明我们要做搜索分页
            result = await reqSearchProducts({pageNum, pageSize: PAGE_SIZE, searchType, searchName})
        }else { // 一般的分页请求
            result =  await reqProducts(pageNum, PAGE_SIZE);
        }
        
        this.setState({loading: false});
        
        if(result.status === 0) {
            const { total, list } = result.data;
            this.setState({
                total, 
                products: list
            });
        }
    }

    // 更新指定商品的状态
    updateStatus = async (productId, status) => {
        const result = await reqUpdateProductStatus(productId, status);
        if(result.status === 0) {
            message.success('更新商品成功');
            this.getProducts(this.pageNum);
        }
    }

    // 初始化数据
    UNSAFE_componentWillMount() {
        this.initColumns();
    }

    // 发请求
    componentDidMount() {
        this.getProducts(1);
    }

    render() {

        const { products, total, loading, searchType, searchName} = this.state;

        const title = (
            <span>
                <Select 
                    value={searchType}
                    style={{width: 150}} 
                    onChange={value => this.setState({searchType: value})}
                >
                    <Option key='productName' value='productName'>按名称搜索</Option>
                    <Option key='productDesc' value='productDesc'>按描述搜索</Option>
                </Select>
                <Input 
                    placeholder='关键字' 
                    style={{width: 150, margin: '0 10px'}} 
                    value={searchName} 
                    onChange={event => this.setState({searchName: event.target.value})}
                    />
                <Button type='primary' onClick={() => this.getProducts(1)}>搜索</Button>
            </span>
        );

        const extra = (
            <span>
                <Button type='primary' onClick={() => {this.props.history.push('/product/addupdate')}}>
                    <Icon type='plus'/> 
                    添加商品
                </Button>
            </span>
        );
        return (

            
            <Card title={title} extra={extra}>
                <Table 
                bordered
                rowKey='_id'
                loading={loading}
                dataSource={products}
                columns={this.columns}
                pagination={{
                    current: this.pageNum,
                    total, 
                    defaultPageSize: PAGE_SIZE, 
                    showQuickJumper: true, 
                    // onChange: () => {this.getProducts(pageNum)},
                    onChange: this.getProducts
                }}
                /> 
            </Card>
        )
    }
}